<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/5
 * Time: 13:34
 */
namespace app\api\controller\followmanage;
use app\api\controller\common\ApiBase;
use Think\Db;
use app\api\controller\common\CommonPlus;
use app\api\model\Admin as AdminModel;
use think\Controller;
class Companyfollow extends Controller
{
    protected $admin;
    protected $model = null;
    private $data = [
        'id'=>'序号',
        'zs_name'=>'展商名称',
        'zs_status'=>'展商状态',
        'jbcz'=>'基本操作',
        'ywy'=>'业务员',
        'zw_number'=>'展位号',
        'zw_type'=>'展位类别',
        'zw_area'=>'展位面积',
        'zp_type'=>'展品类别',
        'source'=>'来源',
        'lb'=>'连报',
        'sale_jd'=>'销售进度',
        'time'=>'最后联络时间',
        'member_grade'=>'会员等级',
        'member_id'=>'会员编号',
        'zs_id'=>'展商编号',
        'zs_type'=>'展商类别',
    ];
    private $status_name =[
        '-1'=>'不参展',
        '-2'=>'退展展商',
        '0'=>'未联系',
        '1'=>'已联系',
        '2'=>'有意向',
        '3'=>'预定展商',
        '4'=>'签约展商',
        '5'=>'部分付款',
        '6'=>'全部付款',
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('CompanyFollow');
    }

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    /**
     *展商可筛选字段显示
     **/
    public function screenField(){
        $data = $this->data;
        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }

    /**
     * 重新分配
     * @return \think\response\Json|void
     */
    public function give(){
        $com =new CommonPlus();
        $id = $this->request->param('id');
        $data['sale_id'] = $this->admin['id'];
        $member_id = $this->request->param('member_id');
        $data['member_id'] = $member_id;
        $exhibition_id = $this->request->param('exhibition_id');//业务员id
        $data['update_time'] = time();
        $data['protection_time'] = time();
        $data['back'] = 3;
        #数据验证
        if(empty($id)){
            return json(['code'=>0,'msg'=>'公海数据有误']);
        }

        if(empty($data['member_id'])){
            return json(['code'=>0,'msg'=>'业务员有误']);
        }

        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $id = explode(',',$id);
        $protectTotal=db($tabName)->field('company_id1')->where(['member_id'=>$member_id,'status'=>array('lt',5)])->select();
        $protectIds=array_column($protectTotal,'company_id1');
        $oldTotal=db('company_label')->where(['company_id'=>array('in',implode(",", $protectIds)),'label'=>'老展商'])->count('DISTINCT company_id');
        $counts=count($protectTotal)-$oldTotal;
        $max_number=db('max_number')->where(['uid'=>$member_id,'exhibition_id'=>$exhibition_id])->value('max_number');
        $max_number=$max_number?$max_number:30;
        if(($counts+count($id))>$max_number){
            return json(['code'=>0,'msg'=>'操作失败！已超过最大展商保护数量,现剩余'.($max_number-$counts)."个名额"]);
        }
        $is = true;
        $msg = '';
        //首先进行数据验证
        foreach ($id as $val){
            #重复分配验证
            $r = db($tabName)->where(['status'=>['<>',-1],'id'=>intval($val)])->find();
            if($r){
                //防止重复数据出现
                if($r['status'] == 1){$is=false;$msg='id:'.$val.'已联系展商不可重新分配';break;}
                else if($r['status'] == 2){$is=false;$msg='id:'.$val.'有意向展商不可重新分配';break;}
                else if($r['status'] == 3){$is=false;$msg='id:'.$val.'预定展商不可重新分配';break;}
                else if($r['status'] == 4){$is=false;$msg='id:'.$val.'签约展商不可重新分配';break;}
            }else{
                $is=false;$msg='操作失败';break;
            }
        }

        if(!$is){
            return json(['code'=>0,'msg'=>$msg]);
        }

        foreach ($id as $v){
            $result=db($tabName)->where(['id'=>$v])->update($data);
            //记录添加
            $com->companyLog($exhibition_id,'潜在展商-将展商进行重新分配',$member_id,$v);
            if(!$result){
                $is=false;
                array_push($errorArr,$v);
            }
        }
        if($is){
            return json(['code'=>1,'msg'=>'操作成功']);
        }else{
            $errIds= implode('，',$errorArr);
            return json(['code'=>0,'msg'=>$errIds.'展商未操作成功']);
        }
    }

    /**
     * 业务员自提数据
     * 公海表 status 改为3自提
     */

    public function gives(){
        $com =new CommonPlus();
        $public_id = $this->request->param('cid');//公司id
        $exhibition_id = $this->request->param('exhibition_id'); //展会id
        $data['sale_id'] = $this->admin['id'];//分配人id
        $member_id= $this->admin['id'];//业务员id
        $data['member_id'] = $member_id;
        $data['update_time'] = time();
        $data['protection_time'] = time();
        $data['back'] = 2;
        #数据验证
        if(empty($public_id)){
            return json(['code'=>0,'msg'=>'公海数据有误']);
        }
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        if(empty($data['member_id'])){
            return json(['code'=>0,'msg'=>'业务员有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        //先查询记录是否存在
        $where['id'] = array('in', $public_id);
        $where['member_id'] = array('neq',0);
        $res = db($tabName)->where($where)->select();
        if($res){
            return json(['code'=>0,'msg'=>'数据已被分配']);
        }
        $errorArr=array();
        $public_id = explode(',',$public_id);
        $protectTotal=db($tabName)->field('company_id1')->where(['member_id'=>$member_id,'status'=>array('lt',5)])->select();
        $protectIds=array_column($protectTotal,'company_id1');
        $oldTotal=db('company_label')->where(['company_id'=>array('in',implode(",", $protectIds)),'label'=>'老展商'])->count('DISTINCT company_id');
        $counts=count($protectTotal)-$oldTotal;
        $max_number=db('max_number')->where(['uid'=>$member_id,'exhibition_id'=>$exhibition_id])->value('max_number');
        $max_number=$max_number?$max_number:30;
        if(($counts+count($public_id))>$max_number){
            return json(['code'=>0,'msg'=>'操作失败！已超过最大展商保护数量,现剩余'.($max_number-$counts)."个名额"]);
        }
        $is = true;
        $errId='';
        $errMsg="";
        foreach ($public_id as $v){
            $zsRes=db($tabName)->where(['id'=>$v])->find();
            if($zsRes){
                $ag=db($tabName)->where(['member_id'=>array('gt',0),'company_name'=>$zsRes['company_name']])->find();
                if($ag){
                    $is=true;
                    $errId=$v;
                    $errMsg='数据已被分配';
                    break;
                }else{
                    $result=db($tabName)->where(['id'=>$v])->update($data);
                    $com->companyLog($exhibition_id,'潜在展商-将展商进行自提保护',$member_id,$v);
                }
            }else{
                $is=true;
                $errId=$v;
                $errMsg='展商数据错误';
                break;
            }
        }
        if($is){
            return json(['code'=>1,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>$errId.$errMsg]);
        }
    }

    /**
     * 进入公海后映射公司详情表
     * $id 公司id 公海id
     */
    private function tbCompany($id,$pid){
        //查询基础库里面是否有此基础数据备份了
        $public_company = db('company_public_company')->where(['c_id'=>$id,'public_id'=>$pid])->find();
        if( $public_company){
            //已经有值直接抛出
            return true;
        }
        Db::startTrans();
        try {
            $company = db('company')->where(['id'=>$id])->find();
            unset($company['id']);
            $data = $company;
            $data['c_id'] = $id;
            $data['public_id'] = $pid;
            db('company_public_company')->insert($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            //如获取到异常信息，对所有表的删、改、写操作，都会回滚至操作前的状态：
            Db::rollback();
            return false;
        }
    }



    /**
     * 更新进度
     */
    public function updateFollow(){
        $data['status'] = $this->request->param('status');
        $data['update_time'] = time();
        $where['id'] = $this->request->param('id');
        $remark = $this->request->param('remark');//跟进备注
        $intention = $this->request->param('intention');//客户意向
        $time =$this->request->param('time');//联络时间
        $status = $this->request->param('log_status');//联络状态
        $exhibition_id = $this->request->param('exhibition_id');//业务员id
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $where['back'] = array('<>',1);//退回公海数据不能更改
        $rs = db($tabName)->where($where)->find();
        if(!$rs){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
//        if($data['status']<=$rs['status']){
//            return json(['code'=>0,'msg'=>'更改状态有误']);
//        }
        $r = db($tabName)->where($where)->update($data);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
//        if(!empty($remark)){
        #操作记录
        $dataLog['public_id'] = $rs['id'];
        $dataLog['follow_id'] = $rs['id'];//私海id
        $dataLog['member_id'] = $this->admin['id'];
        $dataLog['status'] = $data['status'];
        $dataLog['content'] = $remark;
        $dataLog['intention'] = $intention;//客户意向
        $dataLog['exhibition_id'] = $exhibition_id;//客户意向
        $dataLog['time'] = strtotime($time);//联络时间
        $dataLog['create_time'] =  time();
        model('FollowLog')->insertData($dataLog);
//        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 退回公海
     */
    public function backFollow(){
        $com =new CommonPlus();
        $data['back'] = 1;
        $data['status'] = 0;
        $data['sale_id'] = 0;
        $data['member_id'] = 0;
        $data['protection_time'] = null;
        $where['id'] = $this->request->param('id');
        $exhibition_id = $this->request->param('exhibition_id');
        $member_id= $this->admin['id'];//业务员id
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $rs = db($tabName)->where($where)->find();
        if(!$rs){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        if($member_id!=$rs['member_id']){
            if($rs['status'] == 1){return json(['code'=>0,'msg'=>'已联系展商不可退回']);}
            else if($rs['status'] == 2){return json(['code'=>0,'msg'=>'有意向展商不可退回']);}
            else if($rs['status'] == 3){return json(['code'=>0,'msg'=>'预定展商不可退回']);}
            else if($rs['status'] == 4){return json(['code'=>0,'msg'=>'签约展商不可退回']);}
        }

        $both=db('booth')->where(['exhibition_id'=>$exhibition_id,'agent_id'=>$where['id'],'is_delete'=>0])->select();
        if(!empty($both)){
            foreach ($both as $v){
                db('booth')->where(['id'=>$v['id']])->update(['agent_id'=>null]);
            }
        }
        $r = db($tabName)->where($where)->update($data);
        //记录添加
        $com->companyLog($exhibition_id,'将展商-'.$rs['company_name'].'退回公海','',$rs['id']);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        #更改公海状态
        //$r = model('CompanyPublic')->updateBywhere(['status'=>-1],['id'=>$rs['public_id']]);
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 批量退回公海
     */
    public function backFollowall(){
        $com =new CommonPlus();
        $id = $this->request->param('id');
        $exhibition_id = $this->request->param('exhibition_id');
        $ids = explode(',',$id);
        $data['back'] = 1;
        $data['status'] = 0;
        $data['sale_id'] = 0;
        $data['member_id'] = 0;
        $member_id= $this->admin['id'];//业务员id
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $public_ids =array();
        $isOk=true;
        $msg='';
        foreach ($ids as $id){
            $r = db($tabName)->where(['id'=>$id])->find();
            if(!$r){
                $isOk=false;$msg='id:'.$id.'记录不存在,批量删除失败';break;
            }
            if($r['member_id']!=$member_id){
                if($r['status'] == 1){ $isOk=false;$msg='id:'.$id.'已联系展商不可退回';break;}
                else if($r['status'] == 2){$isOk=false;$msg='id:'.$id.'有意向展商不可退回';break;}
                else if($r['status'] == 3){$isOk=false;$msg='id:'.$id.'预定展商不可退回';break;}
                else if($r['status'] == 4){$isOk=false;$msg='id:'.$id.'签约展商不可退回';break;}
            }
            $public_ids[] = $r['id'];
            $com->companyLog($exhibition_id,'将展商-'.$r['company_name'].'退回公海','',$id);
        }


        if(!$isOk){
            return json(['code'=>0,'msg'=>$msg]);
        }

        foreach ($ids as $cid){
            //$r = db($tabName)->where(['id'=>$id])->find();
            $both=db('booth')->where(['exhibition_id'=>$exhibition_id,'agent_id'=>intval($cid),'is_delete'=>0])->select();
            //记录添加
            if(!empty($both)){
                foreach ($both as $v){
                    db('booth')->where(['id'=>$v['id']])->update(['agent_id'=>null]);
                }
            }
        }

        Db::startTrans();
        try {
            $map['id'] = array('in',$ids);
            //$this->model->updateBywhere($data,$map);
            db($tabName)->where($map)->update($data);
            //查询公海
            //model('CompanyPublic')->updateBywhere(['status'=>-1],['id'=>array('in',$public_ids)]);
//            $this->model->deleteWhere($map)
            Db::commit();
            return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
        } catch (\Exception $e) {
            //如获取到异常信息，对所有表的删、改、写操作，都会回滚至操作前的状态：
            Db::rollback();
            return json(['code'=>0,'msg'=>'操作失败，请重试','data'=>'']);
        }

    }

    /**
     * 合同提交审核
     */
    public function subContract(){

        $data['contract_id'] = $this->request->param('contract_id');
        $data['follow_id'] = $this->request->param('follow_id');
        $booth_id = $this->request->param('booth_id');

        $info = $this->model->findWhere(['id'=>$data['follow_id']]);
        if(!$info){
            return json(['code'=>0,'msg'=>'跟踪记录不存在']);
        }

        $exhibition_id = db('booth')->where('id',$booth_id)->value('exhibition_id');

        $data['exhibition_id'] = $exhibition_id;
        $data['booth_id'] = $booth_id;
        $data['company_id'] = $info['company_id'];
        $data['member_id'] = $info['member_id'];
        $data['status'] = 0;
        $data['back'] = 0;
        $data['create_time'] = time();
        $r = model('CompanyFollowContract')->insertData($data);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        #更新展位
        model('Booth')->updateBywhere(['member_id'=>$this->admin['id']],['id'=>$booth_id]);

        return json(['code'=>1,'msg'=>'操作成功']);
    }
    /**
     * 私海列表
     * @param member_id,public_id,sale_id
     */
    public function followList(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize = input('pageSize');
        $pagesize = empty($pagesize)?10:$pagesize;//吗默认为10
        $where['pc.member_id'] = array('neq',0);//退回公海的不显示
        $status = $this->request->param('status');
        $keyword =input('keyword');
        $exhibition_id=$this->request->param('exhibition_id');
        $category=$this->request->param('category');
        $category_product=$this->request->param('category_product');
        $member_id=$this->request->param('member_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        if (!empty($keyword)) {
            $where['pc.company_name'] = array('like', '%' . trim($keyword) . '%');
        }
        if (!empty($category)) {
            $where['pc.category_id']=array('like', '%' . trim($category) . '%');

        }
        if(!empty($category_product)){
            $where['pc.second_category_id']=array('like', '%' . trim($category_product) . '%');
        }


        //当前用户权限
        $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
        if(!$role_id && $this->admin['is_super']==0){
            return json(['code'=>0,'msg'=>'角色不存在']);
        }
        $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
        if($member_id){
            $where['pc.member_id'] = $member_id;
        }else{
            if($this->admin['is_super'] == 1){
                //不加限制条件
            }else{
                if($is_gl == 1){

                    $w['org_id_tree'] = ['like', "%".$this->admin['org_id']."%"];
                    //所有所属组织的用户 id
                    $adminarr =db('admin')->field('id')->where($w)->select();
                    $admin_ids = array_column($adminarr,'id');
                    $where['pc.member_id'] = array('in',$admin_ids);
                }else{
                    $where['pc.member_id'] = $this->admin['id'];
                }
            }
        }
        if($status||$status==="0"){
            $where['pc.status'] = array('in',$status);
        }
        // if(!empty($this->request->param('project_id'))){
        //     $where['p.project_id'] = $this->request->param('project_id');
        // }


        //查询可优化
        $list = Db::name($tabName)
            ->alias('pc')
            ->field('pc.id,pc.protection_time,pc.category_id,pc.update_time,pc.contract_num,pc.data_from,pc.company_name,pc.company_id1,pc.area_city,pc.info_level,pc.name_cn,pc.company_address,pc.link,pc.contact,pc.category_id,pc.second_category_id,pc.status,pc.back,pc.status,pc.htid,pc.member_id,pc.both_id,a.id as aid,a.realname,b.number,b.area,b.price_type')
            ->join('admin a','pc.member_id=a.id','left')
            ->join('booth b','pc.both_id=b.id','left')
            ->where($where)->order('pc.update_time desc')
            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->select();
        foreach ($list as $k =>&$v){
            //最近联络时间
            $where1['follow_id'] = $v['id'];
            $where1['exhibition_id'] = $exhibition_id;
            $FollowLog = model('FollowLog')->where($where1)->order('id desc')->select();
            //查询展位号数据
            $v['followlog'] = $FollowLog?$FollowLog[0]:'';
            $bsql="select b.*,pt.title as type_title,pt.price as type_price from crm_booth as b left join crm_booth_mold as pt on pt.id = b.price_type where b.id in (select id_zwei from crm_contract where id_zhui=".$exhibition_id." and id_zs=".$v['id']." and is_delete=0) and b.is_delete=0 order by b.id desc";
            $booth=Db::query($bsql);
            $contract = db('contract')->where(['id_zs'=>$v['id'],'id_zhui'=>$exhibition_id,'is_delete'=>0])->order('id desc')->select();
            $v['finance_list']=array();
            $v['finance_total']=0;
            $v['billing_total']=db('billing')->where(['is_delete'=>0,'billing_status'=>2,'company_id'=>$v['id'],'exhibition_id'=>$exhibition_id])->count();
            if(count($contract)>0){
                $contractIds=array_column($contract,'id');
                $v['finance_list']=db('finance')->where(['contract_id'=>array('in',implode(",", $contractIds)),'is_delete'=>0])->select();
                $v['finance_total']=db('finance')->where(['contract_id'=>array('in',implode(",", $contractIds)),'is_delete'=>0])->sum('fee');
            }
            $v['booth'] = $booth?$booth:[];
            $v['contract_list'] = $contract?$contract:[];
            $v['old_label']=db('company_label')->where(['company_id'=>$v['company_id1'],'label'=>'老展商','exhibition_id'=>$exhibition_id])->find();
            unset($booth);
            unset($FollowLog);
        }
        $total =  Db::name($tabName)
            ->alias('pc')
            ->field('pc.id')
            ->join('admin a','pc.member_id=a.id','left')
            ->join('booth b','pc.both_id=b.id','left')
            ->where($where)
            ->count();
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }


    /**
     * 展商面板列表
     */
    public function penalList(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            if (empty($admin)) {
                return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
            }
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : null;
            if (!$exhibition_id) {
                return json(array('code' => '0', 'msg' => '展会信息错误为空'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $param=' AND is_delete=0 ';
            if($admin['is_super'] == 1){
                //不加任何条件
                $param.=" AND member_id>0 ";
            }else{
                //是否管理员
                $is_gl=DB::name('role')
                    ->alias('r')
                    ->field('is_gl')
                    ->join('admin_role a','r.id=a.role_id','left')
                    ->where(['a.admin_id'=>$admin['id'],'r.is_gl'=>1])
                    ->select();
                if(!empty($is_gl)){//管理员
                    $param.=" AND member_id in (SELECT id FROM crm_admin WHERE org_id_tree LIKE '%".$admin['org_id']."%') ";
                }else{
                    $param.=" AND member_id=".$admin['id'];
                }
            }

            if($status || $status==='0'){
                $param.=" AND status in (".$status.") ";
            }
            $sql="SELECT id,company_name,status FROM crm_".$tabName." WHERE 1=1 ".$param;
            $list=Db::query($sql);
            return json(array('code' => '1', 'msg' => '操作成功','data'=>$list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 展位列表查询
     */
    public function zwList(){
        $id = $this->request->param('id');
        $exhibition_id=$this->request->param('exhibition_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展商信息错误']);
        }
        $contract_bootlsit=db('contract')->where(['id_zs'=>$id,'id_zhui'=>$exhibition_id,'is_delete'=>0])->select();
        $list = Db::name('booth')
            ->alias('b')
            ->field('b.*,h.title,pt.title as type_title,pt.price as type_price')
            ->join('hall h','b.hall_id=h.id','left')
            ->join('booth_mold pt','pt.id=b.price_type','left')
            ->where(['b.agent_id'=>$id,'b.exhibition_id'=>$exhibition_id,'b.is_delete'=>0])
            ->select();
//        var_dump($contract_bootlsit);
        if(count($contract_bootlsit)>0){
            $c_booth=[];
            foreach($contract_bootlsit as &$vvv){
                $c_booth[]=$vvv['id_zwei'];
            }
            $c_booth=explode(',',implode(',',$c_booth));
            foreach($list as &$v){
                foreach($c_booth as &$vv){
                    if($v['id'] == $vv){
                        $v['use_status']=1;
                    }
                }
            }
        }
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }


    /**
     * 展位列表查询
     */
    public function contractZwList(){
        $id = $this->request->param('id');//展商id
        $exhibition_id=$this->request->param('exhibition_id');//展会id
        $status = $this->request->param('status');//展商id
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展商信息错误']);
        }
        $contract_bootlsit=db('contract')->where(['id_zs'=>$id,'id_zhui'=>$exhibition_id,'is_delete'=>0])->select();
        $where['b.agent_id']=$id;
        $where['b.exhibition_id']=$exhibition_id;
        $where['b.is_delete']=0;
        if(count($contract_bootlsit)>0){
            $c_booth=[];
            foreach($contract_bootlsit as &$vvv){
                $c_booth[]=$vvv['id_zwei'];
            }
            $where['b.id']=array('not in',implode(',',$c_booth));
        }
        $list = Db::name('booth')
            ->alias('b')
            ->field('b.*,h.title,pt.title as type_title,pt.price as type_price')
            ->join('hall h','b.hall_id=h.id','left')
            ->join('booth_mold pt','pt.id=b.price_type','left')
            ->where($where)
            ->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }

    //跟随函数
    public function getBootListResult($id,$exhibition_id,$notIn=null){
        $where['b.agent_id']=$id;
        $where['b.exhibition_id']=$exhibition_id;
        if($notIn){
            $where['b.id']=array('not in',$notIn);
        }
        $list = Db::name('booth')
            ->alias('b')
            ->field('b.*,h.title,pt.title as type_title,pt.price as type_price')
            ->join('hall h','b.hall_id=h.id','left')
            ->join('booth_mold pt','pt.id=b.price_type','left')
            ->where($where)
            ->select();
        return $list;
    }

    /**
     * 最近联系时间
     */
    public function contactTiem(){
        $wheres['id'] = $this->request->param('follow_id');
        $follow = $this->model->findWhere($wheres);
        if(!$follow){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        $where['follow_id'] = $follow['id'];
        $where['public_id'] = $follow['public_id'];
        $where['member_id'] = $this->admin['id'];

        $FollowLog = model('FollowLog')->where($where)->order('time desc')->find();
        $time = date('Y-m-d H:i:s',$FollowLog['time']);
        return json(['code'=>1,'msg'=>'success','data'=>$time]);
    }
    /**
     * 跟进记录列表
     */
    public function logList(){
        $wheres['id'] = $this->request->param('follow_id');
        $exhibition_id=$this->request->param('exhibition_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $follow = db($tabName)->where($wheres)->find();
        if(!$follow){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        $where1['follow_id'] = $follow['id'];
        $where1['exhibition_id'] = $exhibition_id;
//        $where1['member_id'] = $this->admin['id'];

        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize = 10;
        $list = model('FollowLog')->listWherePage($where1,'id desc',($page-1)*$pagesize,$pagesize);
        $total = model('FollowLog')->countWhere($where1);

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total,'page'=>$total,' pagesize'=>$pagesize]]);
    }

    /**
     * 参展历史
     */

    public function czLogList(){
        $id = input('id');//基础库id
        $result=db('exhibition')->field('id,title,create_tablename')->where(['is_delete'=>0])->select();
        $histroyList=array();
        foreach($result as &$v){
            $tabName=$v['create_tablename'];
            $company_public_company =  db($tabName)->field('company_name,status,id')->where(['company_id1'=>$id,'status'=>array('egt',3)])->find();
            if(!empty($company_public_company)){
                $v['company_public_company'] = $company_public_company;
                $bsql="select b.*,pt.title as type_title,pt.price as type_price from crm_booth as b left join crm_booth_mold as pt on pt.id = b.price_type where b.id in (select id_zwei from crm_contract where id_zhui=".$v['id']." and id_zs=".$company_public_company['id']." and is_delete=0) and b.is_delete=0 order by b.id desc";
                $v['booth']=Db::query($bsql);
                $v['contract'] = db('contract')->field('id,money_total_ht,ht_name')->where(['id_zs'=>$company_public_company['id'],'is_delete'=>0])->select();
                $v['status']=$company_public_company['status'];
                $histroyList[]=$v;
            }
        }
        unset($v);
        return json(['code'=>1,'msg'=>'success','data'=>$histroyList]);
    }


    /**
     *获取展商标签
     **/
    public function getLable(){
        $follow_id = input('follow_id');//展商id
        $list= db('company_follow_label')->where(['follow_id'=>$follow_id])->select();
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }

    /**
     *添加展商标签
     **/
    public function addLable(){
        $follow_id = input('follow_id');//展商id
        $name = input('name');//展商标签
        $data['follow_id'] = $follow_id;
        $data['name'] = $name;
        $label = db('company_follow_label')->insert($data);
        if($label){
            return json(['code'=>1,'msg'=>'success']);
        }else{
            return json(['code'=>0,'msg'=>'添加失败']);
        }

    }
    /**
     *修改展商标签
     **/
    public function eitLable(){
        $id= input('id');
        $name = input('name');//展商标签
        $data['name'] = $name;
        $label = db('company_follow_label')->where(['id'=>$id])->update($data);
        if($label){
            return json(['code'=>1,'msg'=>'success']);
        }else{
            return json(['code'=>0,'msg'=>'修改失败']);
        }

    }
    /**
     *删除展商标签
     **/
    public function delLable(){
        $id= input('id');
        $label = db('company_follow_label')->where(['id'=>$id])->delete();
        if($label){
            return json(['code'=>1,'msg'=>'success']);
        }else{
            return json(['code'=>0,'msg'=>'删除失败']);
        }

    }

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
                $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
                if($is_gl == 1){
                    $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
                }else{
                    $where['a.id']=$this->admin['id'];
                }
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 获取当前管理员展会列表
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserExhib(){

        $where['merchants_manager'] = $this->admin['id'];
        $where['endtime'] = array('LT',date('Y-m-d',time()));
        $where['is_delete'] = 0;
        $data = db('exhibition')->field('title,id')->where($where)->select();

        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }

    /**
     * 基本信息
     * @return \think\response\Json|void
     */
    public function companyDetail()
    {
        $exhibition_id =$this->request->param('exhibition_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $id = input('id');
        $where = ['id'=>$id];
        $info = db($tabName)->where($where)->find();
        $bSql="select * from crm_booth where id in (select id_zwei from crm_contract where id_zhui=".$exhibition_id." and id_zs=".$id." and is_delete=0) and is_delete=0";
        $both_list=Db::query($bSql);
        return json(['code' => 1, 'msg' => 'success', 'data' => $info,'booth'=>$both_list]);
    }

    /**
     * 获取此页面所有下拉
     *params 要查询的表名 ，主级需预先存表，防止错误不返回
     */

    public function getQyFormAllxla()
    {
        $comp = new CommonPlus();
        $params = array('tbarrs' => array('xiala_gsxz', 'xiala_gsxt', 'xiala_gslevel', 'xiala_sshy', 'xiala_ywxz'));

        $list = $comp->selAll_xla_BytypeF1('gsxz', $params);
        if (!$list) {
            return json(['code' => 0, 'msg' => 'error', 'data' => ['list' => $list]]);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list]]);
    }

    /**
     * 企业列表 内部调用 做筛选
     *
     */
    public function zslinkuserListall(){

        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page');
        $where=array();
        $page = max(1,intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0; //回头问下

        if(!empty($keyword)){
            $where['company_name|company_name_en'] = array('like','%'.$keyword.'%');
        }
        $list = model('Companyfollowlinkuser')->listAll($where,'id desc',($page-1)*$pagesize,$pagesize);
        // $total = $this->model->countWhere($where);
        $total=1;
        //return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total,'countpage'=>ceil($total/$pagesize)]]);
        return json_encode($list);
    }
    /**
     * 获取展会下所有展厅
     */
    public function getAllHall(){
        $id = input('id');
        if(empty($id)){
            return json(['code'=>1,'msg'=>'参数有误']);
        }
        $sql=" select * from crm_hall where pavilion_id in (select id from crm_pavilion where exhibition_id=".$id." and is_delete=0) and is_delete=0";
        $list=Db::query($sql);
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }
    /**
     * 展位列表
     */
    public function BoothgetList(){
        if (request()->isPost()) {
            $post = input('post.');
            $page = isset($post['page']) && $post['page'] != '' ? $post['page']: 1;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $keyword = isset($post['keyword']) && $post['keyword'] != '' ? $post['keyword'] : 0;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $hall_id = isset($post['hall_id']) && $post['hall_id'] != '' ? $post['hall_id'] : 0;
            if(!$exhibition_id || empty($exhibition_id)){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $parms=" b.is_delete=0 and b.exhibition_id=$exhibition_id";
            if($keyword){
                $parms.=" and b.number like '%$keyword%' ";
            }
            if($hall_id){
                $parms.=" and b.hall_id=$hall_id ";
            }
            $sql=" select b.*,h.title as hall_title from crm_booth as b";
            $sql.=" left join crm_hall as h on h.id=b.hall_id ";
            $sql.=" where 1=1 and ".$parms;
            $total=Db::query($sql);
            $sql.=" order by b.id desc";
            $sql.=" limit ".($page-1)*$pageSize.",$pageSize";
            $list=Db::query($sql);
            return json(['code' => 1, 'msg' => '操作成功', 'data' => ['list'=>$list,'count'=>count($total)]]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

//    /**
//     * 展会下的展馆列表
//     * @return \think\response\Json|void
//     */
//    public function ExhibpavilgetList(){
//        $exhib_id = $this->request->param('exhib_id');
//        $list = model('Pavilion')->getListByExhib(['exhibition_id'=>$exhib_id]);
//        return json(['code'=>1,'msg'=>'success','data'=>$list]);
//    }

    /**
     * 展馆列表
     */
    public function ExhibpavilgetList(){
        $keyword = $this->request->param('keyword');
        $page = $this->request->param('page');

        $page = max(1,intval($page));
        $pagesize = 10;

        if(!empty(input('exhibition_id'))){
            $where['exhibition_id'] = input('exhibition_id');
        }

        $where['a.is_delete'] = 0;
        $wheres['is_delete'] = 0;
        if(!empty($keyword)){
            $wheres['title'] = $where['a.title'] = array('like','%'.$keyword.'%');
        }

        //$list = $this->model->listWherePage($where,'id desc',($page-1)*$pagesize,$pagesize);
        $list = db('Pavilion')->alias('a')->field('a.*,b.title as exh_title')->join('exhibition b','a.exhibition_id=b.id','left')->where($where)->order('id desc')->limit(($page-1)*$pagesize.','.$pagesize)->select();
        $total = model('Pavilion')->countWhere($wheres);

        if(!empty($list)){
            foreach ($list as &$v){
                $v['exhibition_info'] = model('Pavilion')->findExhibition($v['id']);
            }
            unset($v);
        }

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    /**
     * 展厅列表
     */
    public function HallgetList(){
        $keyword = $this->request->param('keyword');
        $pavilion_id = $this->request->param('pavilion_id');
        $page = $this->request->param('page');

        $page = max(1,intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0;
//        if(!empty($keyword)){
//            $where['title|number'] = array('like','%'.$keyword.'%');
//        }
//
//        if(!empty($pavilion_id)){
//            $where['pavilion_id'] = $pavilion_id;
//        }
//
//        $list = $this->model->listWherePage($where,'id desc',($page-1)*$pagesize,$pagesize);
//        $total = $this->model->countWhere($where);
        $whereOr = [];
        if(!empty($keyword)){
            $whereOr['title'] = array('like','%'.$keyword.'%');
//            $whereOr['title'] = array('like','%'.$keyword.'%','OR');
//            $whereOr['number'] = array('like','%'.$keyword.'%','OR');
        }

        if(!empty($pavilion_id)){
            $where['pavilion_id'] = $pavilion_id;
        }
        $list = model('Hall')->where($whereOr)->where($where)->order('id desc')->limit(($page-1)*$pagesize.','.$pagesize)->select();
        $total =  model('Hall')->where($whereOr)->where($where)->count();

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    /**
     * 合同列表 多关联
     */
    public function contractList(){
        $page = $this->request->param('page');
        $page=$page?$page:1;
        $pageSize = $this->request->param('pageSize');
        $pageSize=$pageSize?$pageSize:10;
        $exhibition = $this->request->param('exhibition');
        $member_id = $this->admin['id'];//分配人id
        if(empty($exhibition)){
            return json(['code'=>-1,'msg'=>'缺少关键主键展会id']);
        }
        $tabName=$this->getTabName($exhibition);
        $id_zs = input('id_zs');
        $id_zs = isset($id_zs) && $id_zs != '' ? $id_zs : '';
        $res=db($tabName)->where(['id'=>$id_zs])->find();
        if(!$res){
            return json(['code'=>-1,'msg'=>'缺少关键主键展商id']);
        }
        $where['h.is_delete'] = 0;
        $where['h.id_zs'] = $id_zs;
        if($member_id!=1){
            $where['h.create_uid'] = $member_id;
        }
        $where['h.id_zhui'] = $exhibition;
        $list = db('contract')
            ->alias('h')
            ->field('h.*,e.id exhibition_id,e.title,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->order('id desc')
            ->limit(($page-1)*$pageSize.','.$pageSize)
            ->select();

        $total = db('contract')
            ->alias('h')
            ->field('h*,e.id as exhibition_id,e.name,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->count();

        if(!empty($list)){
            $ev['status']=array('gt',1);
            $ev['is_delete']=0;
            foreach ($list as &$v){
                $ev['contract_id']=$v['id'];
                $ftotal=db('finance')->field('sum(fee) as f_total')->where($ev)->select();
                $v['f_total'] =  empty($ftotal)?'0.00':$ftotal[0]['f_total'];
            }
            unset($v);
        }

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);

    }

    /**
     * 合同基本信息
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function contractDetail()
    {
        $com = new CommonPlus();
        $id = $this->request->param('id');

        $where['id'] = $id;
        //$where['is_delete'] = 0;
        $info = model('Contractmgr')->findWhere($where);

        // 获取 D表
        $where1 = array('mid' => $id,'is_delete'=>0);
        $r1 = $com->sel_com_fxlist("f", $where1, "contract_detail");
        $info['D_detail'] = $r1; // 表单的明细

        $r2 = $com->sel_com_fxlist("f", $where1, "contract_detail_plan");
        $info['plan_detail'] = $r2; // 付款计划 明细条数
        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }

    public function Financeindex(){
        $page = $this->request->param('page');
        $exhibition_id=$this->request->param('exhibition_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键主键展会id']);
        }
        $follow_id=$this->request->param('follow_id');
        if(empty($follow_id)){
            return json(['code'=>0,'msg'=>'缺少关键主键展商id']);
        }
        $page = max(1,intval($page));
        $pagesize = empty(input('pageSize',10))?10:input('pageSize',10);
        $where =array();
        $where['a.is_delete'] = 0;
        $where['b.create_uid'] = $this->admin['id'];
        $where['b.id_zhui'] = $exhibition_id;
        $where['b.id_zs'] = $follow_id;
        $pay_name = input('pay_name');
        if(!empty($pay_name)){
            $where['a.pay_name'] = ['like','%'.$pay_name.'%'];
        }

        $fee = input('fee');
        if(!empty($fee)){
            $where['a.fee'] = $fee;
        }

        $join_type = input('join_type');
        if(!empty($join_type)){
            $where['a.join_type'] = $join_type;
        }

        $company = input('company');
        if(!empty($company)){
            $where['b.name_zs'] = ['like','%'.$company.'%'];
        }
        $is_bill = input('is_bill');
        if(is_numeric($is_bill)&&$is_bill==0){
            $where['a.bill'] = 'null';
        }

        if(is_numeric($is_bill)&&$is_bill==1){
            $where['a.bill'] = 'not null';
        }

        $list = db('finance')
            ->alias('a')
            ->field('a.*,b.name_zs,b.id contract_id,b.id_zhui,b.ht_id,b.create_uid,b.id_zhui,b.id_zs,b.money_total_ht')
            ->join('contract b','a.contract_id=b.id','left')
            ->where($where)
            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->order('a.id desc')
            ->select();

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list]]);
    }
    /**
     * 获取用户的展会列表
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserExhib_czy(){

        $where['merchants_manager'] = input('uid');
        $where['endtime'] = array('LT',date('Y-m-d',time()));
        $where['is_delete'] = 0;
        $data = db('exhibition')->field('title,id')->where($where)->select();

        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }

    /**
     *
     * @return mixed
     */
    public function _before_add(){
        $data['exhibition_id'] = $this->request->param('exhibition_id');
        $data['pavilion_id'] = $this->request->param('pavilion_id');
        $data['hall_id'] = $this->request->param('hall_id');
        $data['area'] = $this->request->param('area');
        //$data['position'] = $this->request->param('position');
        //$data['describe'] = $this->request->param('describe');
        $data['price_type'] = $this->request->param('price_type');
        $data['height'] = $this->request->param('height');
        $data['width'] = $this->request->param('width');
        $data['price'] = $this->request->param('price');
        $data['number']  = $this->request->param('number');
        //$data['sort']  = $this->request->param('sort');
        //$data['agent_id']  = $this->request->param('agent_id');
        return $data;
    }
    /**
     * 新增展位
     * @return \think\response\Json|void
     */
    public function add(){
        $data = $this->_before_add();

        $data['create_time']  = time();
        $data['is_delete']  = 0;
        //查看展位号码是否存在 by lhd 2020.2.10
        $zwh = model('Booth')->where(['number'=>$data['number'],'hall_id'=>$data['hall_id']])->find();
        if($zwh){
            return json(['code'=>0,'msg'=>'展位号不能重复']);
        }

        $r = model('Booth')->insertData($data);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 编辑展位
     * @return \think\response\Json|void
     */
    public function edit(){
        $id = $this->request->param('id');//展位id
        $exhibition_id = $this->request->param('exhibition_id');//展会id
        $agent_id = $this->request->param('agent_id');//展商id
        $zwh = model('Booth')->where(['id'=>$id])->find();
        if(empty($zwh)){
            return json(['code' => 0, 'msg' => '展位号错误']);
        }
        if(empty($exhibition_id)){
            return json(['code' => 0, 'msg' => '展会信息错误']);
        }

        if(empty($exhibition_id)){
            return json(['code' => 0, 'msg' => '展会信息错误']);
        }

        if(empty($agent_id)){//删除展位
            //查是否在合同中

            $sql="select id from crm_contract where 1=1 and id_zhui=$exhibition_id and id_zwei like '%$id%' and is_delete=0";
            $list=Db::query($sql);
            if(is_array($list) && count($list)>0){
                return json(['code' => 0, 'msg' => '此展位已经绑定合同,不可删除']);
            }else{
                $where['id'] = $id;
                $data['agent_id']=0;
                $r=model('Booth')->updateBywhere($data,$where);
            }
        }else{//重新绑定展位
            $where['id'] = $id;
            $data['agent_id']=$agent_id;
            $r=model('Booth')->updateBywhere($data,$where);
        }

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    //展位绑定
    public function bothBindAgent(){
        $id = $this->request->param('id');//展位id
        $exhibition_id = $this->request->param('exhibition_id');//展会id
        $agent_id = $this->request->param('agent_id');//展商id
        if(empty($id)){
            return json(['code' => 0, 'msg' => '展位号错误']);
        }
        if(empty($exhibition_id)){
            return json(['code' => 0, 'msg' => '展会信息错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $zhRes=db($tabName)->where(['id'=>$agent_id])->find();
        if(!$zhRes){
            return json(['code' => 0, 'msg' => '展商信息错误']);
        }
        $sql="select id from crm_".$tabName." where id in (select agent_id from crm_booth where id in(".$id."))";
        $bothRes=Db::query($sql);
        if(count($bothRes)>0){
            return json(['code' => 0, 'msg' => '展位已绑定展商,请重新选择']);
        }
        $upRes=db('booth')->where(['id'=>array('in',$id)])->update(['agent_id'=>$agent_id]);
        if(!$upRes){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    //删除展位
    public function bothDelAgent(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $zhRes=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$zhRes){
                return json(['code' => 0, 'msg' => '展会信息错误']);
            }
            $bothRes=db('booth')->where(['id'=>$id])->find();
            if(!$bothRes){
                return json(['code' => 0, 'msg' => '展位信息错误']);
            }
            $contractRes=db('contract')->field('id_zwei')->where(['is_delete'=>0,'id_zhui'=>$exhibition_id])->select();
            if($contractRes){
                $flag=false;
                foreach ($contractRes as &$v){
                    if(in_array($id,explode(",",$v['id_zwei']))){
                        $flag=true;
                        break;
                    }
                }
                if($flag){
                    return json(['code' => 0, 'msg' => '此展位已在合同中使用,不可删除']);
                }
            }
            $dRes=db('booth')->where(['id'=>$id])->update(['agent_id'=>0]);
            if(!$dRes){
                return json(['code' => 0, 'msg' => '操作失败']);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }



    /**
     * 企业基本信息
     * @return \think\response\Json|void
     */
    public function zslinkuserDetail(){
        // $zsid = $this->request->param('zsid');
        $id = $this->request->param('id'); // 明细 应该是 列表的id

        // $where['zsid'] = $zsid;
        $where['id'] = $id;
        $where['is_delete'] = 0;
        $info = model('Companyfollowlinkuser')->findWhere($where);

        return json(['code'=>1,'msg'=>'success','data'=>$info]);
    }



    /**
     * 新增企业
     * @return \think\response\Json|void
     */
    public function addzslinkuser(){
        //==common
        $create_uid  = $this->admin['id'];
        $remark = $this->request->param('remark');
        //== comon

        $name = $this->request->param('name');     // 姓名
        $zsid = $this->request->param('zsid');// 展商 id
        // $companyid = $this->request->param('companyid');// 企业id
        $sex = $this->request->param('sex'); //
        $positions = $this->request->param('positions');  // 职务
        $duties = $this->request->param('duties');  //  职责
        $department = $this->request->param('department'); // 部门中
        $tel = $this->request->param('tel'); // 电话
        $mobile = $this->request->param('mobile'); //个人手机
        $fax = $this->request->param('fax');  // 传真
        $email = $this->request->param('email');  // email 个人
        $qq = $this->request->param('qq');
        //$wechat = $this->request->param('wechat');
        //$msn = $this->request->param('msn');
        $link_other = $this->request->param('link_other');  // 其他联系方式
        $addr = $this->request->param('addr');  // 地址 个人
        // 2

        $postalcode = $this->request->param('postalcode');  //邮编
        //$country = $this->request->param('country');  //国家
        //$country_code = $this->request->param('country_code');  //国家代码
        $province = $this->request->param('province');  //省份
        //$area = $this->request->param('area');  //区域
        $city = $this->request->param('city');  //市
        $town = $this->request->param('town');  // 区


        // ed
        $data = array('create_uid'=>$create_uid,'remark'=>$remark,'create_time'=>time(),'name'=>$name,
            'zsid'=>$zsid,'sex'=>$sex,'positions'=>$positions,'duties'=>$duties,
            'department'=>$department,'tel'=>$tel,'mobile'=>$mobile,
            'fax'=>$fax,'email'=>$email,'qq'=>$qq,'link_other'=>$link_other,'addr'=>$addr,'postalcode'=>$postalcode,'province'=>$province,
            'town'=>$town,'city'=>$city
        );


        $r = model('Companyfollowlinkuser')->insertData($data);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 人员列表 company_user
     * 前端调用
     */
    public function zslinkuserList(){
        $page = $this->request->param('page');
        $where=array();
        $page = max(1,intval($page));
        $pagesize = 10;
        $zsid = $this->request->param('zsid'); //首次就应该 只是展商id 来的
        if(empty($zsid)){
            return json(['code'=>0,'msg'=>'缺少关键主键展商id']);
        }
        // 查询 st
        $name = $this->request->param('name');
        $depart = $this->request->param('depart');
        $compname = $this->request->param('compname');

        $keyword="";
        if( !empty($name) ){
            $keyword = $name;
            $where['name_cn|surname_cn'] = array('like','%'.$keyword.'%');
        }

        if( !empty($depart) ){
            $keyword = $depart;
            $where['department_cn|department_en'] = array('like','%'.$keyword.'%');
        }
        if( !empty($compname) ){
            $keyword = $compname;
            $where['companyname'] = array('like','%'.$keyword.'%');
        }
        // 条件查询 ed
        $where['zsid'] = $zsid;
        $where['is_delete'] = 0;

        if(!empty($keyword)){
            // $where['company_name|company_name_en'] = array('like','%'.$keyword.'%');
        }

        $list = model('Companyfollowlinkuser')->listWherePage($where,'id desc',($page-1)*$pagesize,$pagesize);
        $total = model('Companyfollowlinkuser')->countWhere($where);

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total,'countpage'=>$total]]);

    }

    /**
     * 删除人员
     */
    public function dellinkuser(){
        // $zsid = $this->request->param('zsid');
        $id = $this->request->param('id');

        $where = ['id'=>$id,'is_delete'=>0];

        $r = model('Companyfollowlinkuser')->countWhere($where);

        if(empty($r)){
            return json(['code'=>0,'msg'=>'记录不存在1，请核实']);
        }

        $r = model('Companyfollowlinkuser')->deleteWhere(['id'=>$id]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }



    public function editzslinkuser(){
        // com
        // $zsid = $this->request->param('zsid'); // 明细的id 还是展商的id 呢
        $id = $this->request->param('id'); //必须
        $create_uid  = $this->admin['id'];
        // com

        //==========
        $remark = $this->request->param('remark');


        //== comon

        $name = $this->request->param('name');     // 姓名
        //$companyid = $this->request->param('zsid');// 企业id
        $sex = $this->request->param('sex'); //
        $positions = $this->request->param('positions');  // 职务
        $duties = $this->request->param('duties');  //  职责
        $department = $this->request->param('department'); // 部门中
        $tel = $this->request->param('tel'); // 电话
        $mobile = $this->request->param('mobile'); //个人手机
        $fax = $this->request->param('fax');  // 传真
        $email = $this->request->param('email');  // email 个人
        $qq = $this->request->param('qq');
        //$wechat = $this->request->param('wechat');
        //$msn = $this->request->param('msn');
        $link_other = $this->request->param('link_other');  // 其他联系方式
        $addr = $this->request->param('addr');  // 地址 个人
        // 2

        $postalcode = $this->request->param('postalcode');  //邮编
        //$country = $this->request->param('country');  //国家
        //$country_code = $this->request->param('country_code');  //国家代码
        $province = $this->request->param('province');  //省份
        //$area = $this->request->param('area');  //区域
        $city = $this->request->param('city');  //市
        $town = $this->request->param('town');  // 区



        // ed
        $data = array('remark'=>$remark,'update_time'=>time(),'name'=>$name,
            'sex'=>$sex,'positions'=>$positions,'duties'=>$duties,
            'department'=>$department,'tel'=>$tel,'mobile'=>$mobile,
            'fax'=>$fax,'email'=>$email,'qq'=>$qq,'link_other'=>$link_other,'addr'=>$addr,'postalcode'=>$postalcode,'province'=>$province,
            'town'=>$town,'city'=>$city
        );
        //=======

        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误，请核查']);
        }

        // $where['zsid'] = $zsid;
        $where['id'] = $id;
        $r = model('Companyfollowlinkuser')->updateBywhere($data,$where);

        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 审核合同
     */
    public function checkContract(){
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键主键合同id']);
        }
        $info = db('contract')->where(['id'=>$id])->find();
        if(!$info){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        $status=$this->request->param('status');
        $data=array();
        if(isset($status)){
            $data['s_status'] = intval($status);
        }
        $back=$this->request->param('back');
        if(isset($back)){
            $data['is_back'] = intval($back);
        }
        $remark=$this->request->param('remark');
        if(isset($remark)){
            $data['remarks'] = $remark;
        }
        $r = db('contract')->where(['id'=>$id])->update($data);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        #添加操作记录
        try {
            $logData['follow_id'] = $info['id'];
            $logData['public_id'] = db('company_follow')->where(['id'=>$info['id_zs']])->value('public_id');
            $logData['member_id'] = $info['create_uid'];
            $logData['content'] = $this->admin['realname'].'操作合同审核，由'.$this->statusArr[$info['s_status']].'变更为'.$this->statusArr[($data['s_status']?$data['s_status']:1)];
            $r = setFollowLog($logData);

        } catch (\Exception $e) {

        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 删除合同
     */
    public function delete(){
        $id = input('id');
        $r = model('CompanyFollowContract')->deleteWhere(['contract_id'=>$id]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }


    /**
     * 企业列表
     */
    public function companyList()
    {
        $page = $this->request->param('page');
        $compname = $this->request->param('compname');
        $exhibition_id = $this->request->param('exhibition_id');
        $page = max(1, intval($page));
        $pagesize = 10;
        $param=" and p.is_delete=0 ";
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键主键展会id']);
        }
        if (!empty($compname)) {
            $param.=" and p.company_name like '%$compname%'";
        }else{
            return json(['code'=>0,'msg'=>'请输入公司名称']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $tabName='crm_'.$tabName;
        $sql2="select p.id,p.mobile,p.tel,p.company_name,z.member_id,a.realname";
        $sql2.=" from crm_company as p ";
        $sql2.=" left join ".$tabName." as z on (LTRIM(RTRIM(z.company_name))=LTRIM(RTRIM(p.company_name)) or z.company_id1=p.id)";
        $sql2.=" left join crm_admin as a on a.id=z.member_id";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by p.id desc";
        $sql2.=" limit ".($page-1)*$pagesize.",$pagesize";
        //var_dump($sql2);die();
        $list=Db::query($sql2);
        $sql21=" select count(p.id) as count1 ";
        $sql21.=" from crm_company as p ";
        $sql21.=" where 1=1 $param";
        $total1=Db::query($sql21);
        $total=$total1[0]['count1']; //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
    }

    //根据展商id查详细信息
    public function getBusinessDetail(){
        $id = $this->request->param('id');
        $exhibition_id = $this->request->param('exhibition_id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键展商id主键']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展会数据错误']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $where['f.id']=$id;
        //查询可优化
        $list = Db::name($tabName)
            ->alias('f')
            ->field('f.*,a.realname,a.mobile')
            ->join('admin a','f.member_id=a.id','left')
            ->where($where)
            ->select();
        if(empty($list)){
            return json(['code'=>0,'msg'=>'查询失败']);
        }
        return json(['code'=>1,'msg'=>'success','data'=>$list[0]]);
    }


    /**
     * 合同管理列表页
     * 模糊查询需后补 暂时先做普版
     */
    public function contractmobanList()
    {
        $keyword = $this->request->param('keyword');
        $template_type = $this->request->param('template_type');
        $project = $this->request->param('project');
        $page = $this->request->param('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 10;
        $where['a.is_delete'] = 0;

        if (!empty($keyword)) {
            $where['a.title'] = array('like', '%' . $keyword . '%');
        }
        if (!empty($template_type)) {
            $where['a.template_type'] = $template_type;
        }
        if (!empty($project)) {
            $where['a.project'] = $project;
        }

        $list =  db('contract_mould_yc')
            ->alias('a')
            ->field('a.id,a.title,a.value,a.template_type,a.project,a.create_time,e.title as e_title,t.contract_name')
            ->join('exhibition e','a.project=e.id','left')
            ->join('contract_type t','a.template_type=t.id','left')
            ->where($where)
            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->order('a.id desc')
            ->select();
        $total = db('contract_mould_yc')
            ->alias('a')
            ->field('a.id,a.title,a.value,a.template_type,a.project,e.title,t.contract_name')
            ->join('exhibition e','a.project=e.id','left')
            ->join('contract_type t','a.template_type=t.id','left')
            ->where($where)
            ->count();
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list?$list:array(), 'total' => $total]]);
    }



    //门楣接口
    public function mmGetList(){
        $exhibition_id =$this->request->param('exhibition_id');
        $id=$this->request->param('id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据错误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展商数据错误']);
        }
        $param=" and m.is_del=0 and m.exhibition_id=$exhibition_id and m.id_zs=$id";
        $sql2="select m.*";
        $sql2.=" from crm_zsmeiban m ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }


    /**
     * 添加
     * @return \think\response\Json|void
     */
    public function mmAdd(){
        $com =new CommonPlus();
        $exhibition_id = $this->request->param('exhibition_id');
        $id_zs = $this->request->param('id_zs');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $data['create_time']=time();
        $data['exhibition_id']= $exhibition_id;
        $data['id_zs']= $id_zs;
        $data['title']=$this->request->param('title');   // 中文
        $data['title_en']=$this->request->param('title_en');//英文
        $data['is_havegb']=$this->request->param('is_havegb')==""? 0 : $this->request->param('is_havegb');

        $res=$com->insert_com_dan($data, '', 'zsmeiban');
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }


    /**
     * 删除
     */
    public function mmdel(){
        $com =new CommonPlus();
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        $tabName='zsmeiban';
        $r = db($tabName)->where(['id'=>$id])->find();
        if(!$r){
            return json(['code'=>0,'msg'=>'记录不存在','data'=>'']);
        }
        $where['id'] = $id;
        $data['is_del']=1;
        $r=$com->edit_com_fxlist($data, $where, $tabName);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }


    /**
     * 基本信息修改
     * @return \think\response\Json|void
     */
    public function mmEdit()
    {
        $com =new CommonPlus();
        // com
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        //$create_uid  = $this->admin['id'];
        $data['update_time']=time();

        $data['title']=$this->request->param('title');   // 姓名
        $data['title_en']=$this->request->param('title_en');
        $data['is_havegb']=$this->request->param('is_havegb')==""? 0 : $this->request->param('is_havegb');
        $data['update_time']=time();


        $where['id'] = $id;
        $tbname="zsmeiban";
        $r=$com->edit_com_fxlist($data, $where, $tbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }


    //胸牌接口

    public function xpGetList(){

        $exhibition_id =$this->request->param('exhibition_id');
        $id=$this->request->param('id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据错误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展商数据错误']);
        }

        $param=" and m.is_del=0 and m.exhibition_id=$exhibition_id and m.id_zs=$id";
        $sql2="select m.*";
        $sql2.=" from crm_zscardattend m ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }


    /**
     * 添加
     * @return \think\response\Json|void
     */
    public function xpAdd(){
        $com =new CommonPlus();
        $exhibition_id = $this->request->param('exhibition_id');
        $id_zs = $this->request->param('id_zs');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        if(empty($company_id)){
            //return json(['code'=>0,'msg'=>'请选择企业','data'=>'']);
        }
        // com
        $data['create_time']=time();
        $data['exhibition_id']=$exhibition_id;
        $data['id_zs']=$id_zs;
        $data['name']=$this->request->param('name');   // 姓名
        $data['name_en']=$this->request->param('name_en');
        $data['mobile']=$this->request->param('mobile');
        $data['positions_cn']=$this->request->param('positions_cn'); // 职务
        $data['positions_en']=$this->request->param('positions_en');
        $data['company_name']=$this->request->param('company_name');
        $data['company_name_en']=$this->request->param('company_name_en'); //
        $res=$com->insert_com_dan($data, '', 'zscardattend');
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }


    /**
     * 删除
     */
    public function xpDel(){
        $com =new CommonPlus();
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        $tabName='zscardattend';
        $r = db($tabName)->where(['id'=>$id])->find();
        if(!$r){
            return json(['code'=>0,'msg'=>'记录不存在','data'=>'']);
        }

        $where['id'] = $id;
        $data['is_del']=1;
        $r=$com->edit_com_fxlist($data, $where, $tabName);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }


    /**
     * 基本信息修改
     * @return \think\response\Json|void
     */
    public function xpEdit()
    {
        $com =new CommonPlus();
        // com
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        //$create_uid  = $this->admin['id'];
        $data['update_time']=time();
        // $selfcontent = $this->request->param('selfcontent'); //自定义表单 理论上只有新增 才有 。。让前台隐藏吧

        $data['update_time']=time();
        // com
        $data['name']=$this->request->param('name');   // 姓名
        $data['name_en']=$this->request->param('name_en');
        $data['mobile']=$this->request->param('mobile');
        $data['positions_cn']=$this->request->param('positions_cn'); // 职务
        $data['positions_en']=$this->request->param('positions_en');
        $data['company_name']=$this->request->param('company_name');
        $data['company_name_en']=$this->request->param('company_name_en'); //


        $where['id'] = $id;
        $tbname="zscardattend";
        $r=$com->edit_com_fxlist($data, $where, $tbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }


    //展品信息
    public function gdGetList(){
        $exhibition_id =$this->request->param('exhibition_id');
        $id=$this->request->param('id');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据错误']);
        }
        if(empty($id)){
            return json(['code'=>0,'msg'=>'展商数据错误']);
        }
        $param=" and m.is_del=0 and m.exhibition_id=$exhibition_id and m.id_zs=$id";
        $sql2="select m.*";
        $sql2.=" from crm_zsgoodszp m ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        foreach($list as &$val){
            $val['pic']=unserialize($val['pic']);
        }
        unset($val);
        return json(['code'=>1,'msg'=>'success','data'=>$list]);
    }

    public function gdAdd(){
        $com =new CommonPlus();
        $exhibition_id = $this->request->param('exhibition_id');
        $id_zs = $this->request->param('id_zs');
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        if(empty($id_zs)){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $data['create_time']=time();
        $data['id_zs']=$id_zs;
        $data['title']=$this->request->param('title');   // 新品名称中文
        $data['exhibition_id']=$exhibition_id;   // 展会id
        $data['title_en']=$this->request->param('title_en');
        $data['price']=$this->request->param('price');
        $data['intro']=$this->request->param('intro');// 新品介绍 中文
        $data['intro_en']=$this->request->param('intro_en');
        $pic=$this->request->param('pic');
        $picarr=json_decode($pic, TRUE);;
        if(is_array($picarr)){
            $data['pic']=serialize($picarr);// 看怎么拼
        }
        $res=$com->insert_com_dan($data, '', 'zsgoodszp');
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }

    /**
     * 删除
     */
    public function gdDel(){
        $com =new CommonPlus();
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        $tabName='zsgoodszp';
        $r = db($tabName)->where(['id'=>$id])->find();
        if(!$r){
            return json(['code'=>0,'msg'=>'记录不存在','data'=>'']);
        }

        $where['id'] = $id;
        $data['is_del']=1;
        $r=$com->edit_com_fxlist($data, $where, $tabName);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试','data'=>'']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>'']);
    }

    public function gdEdit()
    {
        $com =new CommonPlus();
        // com
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        $data['update_time']=time();
        $data['title']=$this->request->param('title');   // 姓名
        $data['title_en']=$this->request->param('title_en');
        $data['price']=$this->request->param('price');
        $data['intro']=$this->request->param('intro');
        $data['intro_en']=$this->request->param('intro_en');
        $pic=$this->request->param('pic');
        $picarr=json_decode($pic, TRUE);;
        if(is_array($picarr)){
            $data['pic']=serialize($picarr);// 看怎么拼
        }
        $where['id'] = $id;
        $tbname="zsgoodszp";
        $where2=array('id'=>$id,'company_name'=>'test');
        $r=$com->edit_com_fxlist($data, $where, $tbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    //生成账号密码
    public function setCompanyAdmin(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $zsData = db($tabName)->where(['id'=>$id])->find();
            if(!$zsData){
                return json(['code'=>0,'msg'=>'展商数据错误']);
            }
            $cRes=db('contract')->where(['id_zs'=>$id,'is_delete'=>0,'s_status'=>1,'id_zhui'=>$exhibition_id])->select();
            if(empty($cRes)){
                return json(['code'=>0,'msg'=>'展商不是签约展商,操作失败']);
            }

            if($zsData['account'] && $zsData['pwd']){
                return json(['code'=>0,'msg'=>'展商已有账号密码,忘记密码请选择重置密码！']);
            }
            $rodom='0000'.$this->genUserNumber($exhibition_id.$id);
            $password=substr(time().'',-6);
            #跟新展商状态，同时生成随机账号，随机密码
            $zsRes=db($tabName)->where(['id'=>$id])->update(['account'=>$rodom,'pwd'=>$password,'update_time'=>time()]);
            if(!$zsRes){
                return json(['code'=>0,'msg'=>'展商状态操作失败，请重试']);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function genUserNumber($prefix=''){
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        return $prefix . $uuid;
    }
    //重置密码
    public function setCompanyPassWord(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $zsData = db($tabName)->where(['id'=>$id])->find();
            if(!$zsData){
                return json(['code'=>0,'msg'=>'展商数据错误']);
            }
            $cRes=db('contract')->where(['id_zs'=>$id,'is_delete'=>0,'s_status'=>1,'id_zhui'=>$exhibition_id])->select();
            if(empty($cRes)){
                return json(['code'=>0,'msg'=>'展商不是签约展商,操作失败']);
            }
            if(!$zsData['account']){
                return json(['code'=>0,'msg'=>'展商无账号']);
            }
            $password=substr(time().'',-6);
            #跟新展商状态，同时生成随机账号，随机密码
            $zsRes=db($tabName)->where(['id'=>$id])->update(['pwd'=>$password,'update_time'=>time()]);
            if(!$zsRes){
                return json(['code'=>0,'msg'=>'展商状态操作失败，请重试']);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //增加合同数量
    public function addcontract(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $num = isset($post['num']) && $post['num'] != '' ? $post['num'] : 1;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $zsData = db($tabName)->where(['id'=>$id])->find();
            if(!$zsData){
                return json(['code'=>0,'msg'=>'展商数据错误']);
            }

            $zsRes=db($tabName)->where(['id'=>$id])->update(['contract_num'=>$num]);
            if(!$zsRes){
                return json(['code'=>0,'msg'=>'操作失败，请重试']);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //判断合同数量
    public function isAddcontract(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $zsData = db($tabName)->where(['id'=>$id])->find();
            if(!$zsData){
                return json(['code'=>0,'msg'=>'展商数据错误']);
            }
            $rnum=db('contract')->where(['id_zs'=>$id,'id_zhui'=>$exhibition_id,'is_delete'=>0])->count();
            if($rnum>=$zsData['contract_num']){
                return json(['code' => 0, 'msg' => '您有退回合同或合同数量不足，退回合同请编辑原合同上传，合同数量请联系管理员增加合同数量！']);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    //会刊详情
    public function publicationDetail(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $tabName=$this->getTabName($exhibition_id);
            $zsData = db($tabName)->where(['id'=>$id,'label'=>1])->find();
            if($zsData){
                if($zsData['country_chukou']){$zsData['country_chukou']=unserialize($zsData['country_chukou']);}
                if($zsData['doselfbrander_info']){$zsData['doselfbrander_info']=unserialize($zsData['doselfbrander_info']);}
                $zsData['both_list']=db('booth')->where(['agent_id'=>$zsData['id']])->select();
                $zsData['old_label']=db('company_label')->where(['company_id'=>$zsData['company_id1'],'label'=>'协会展商'])->find();
            }
            return json(['code' => 1, 'msg' => '操作成功','data'=>$zsData]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }



    // 提取展会
    public function getPreviouslist(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $exList=db('exhibition')->where(['id'=>array('neq',$exhibition_id)])->select();
            return json(['code' => 1, 'msg' => '操作成功','data'=>$exList]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //查询往届展商
    public function searchPreviousCompany(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $pr_exhibition_id = isset($post['pr_exhibition_id']) && $post['pr_exhibition_id'] != '' ? $post['pr_exhibition_id'] : 0;
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            $member_id = $this->admin['id'];
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $exRes=db('exhibition')->where(['id'=>$pr_exhibition_id])->find();
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }

            $tabName=$this->getTabName($exhibition_id);
            $tabNames=$this->getTabName($pr_exhibition_id);
            $sql=" SELECT * from crm_".$tabNames." where company_id1 not in (SELECT company_id1 from crm_".$tabName." where member_id=".$member_id.") and member_id=".$member_id;
            $list=Db::query($sql);
            return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //提取展会保护展商
    public function addPrevious(){
        $com =new CommonPlus();
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $ids = isset($post['ids']) && $post['ids'] != '' ? $post['ids'] : '';
            $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            $member_id = $this->admin['id'];
            if(!$exRes){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            if(!$ids){
                return json(array('code' => '0', 'msg' => '请选择一个展商'));
            }
            $ids=explode(",", $ids);
            $seize=[];
            $error=[];
            $defect=[];
            $tabName=$this->getTabName($exhibition_id);
            for($i=0;$i<count($ids);$i++){
                $cur=db($tabName)->where(['company_id1'=>$ids[$i]])->find();
                if($cur){
                    if($cur['member_id']>0 && $cur['member_id']!=$member_id){
                        $seize[]=$cur['company_name'];
                    }else{
                        $upData['member_id']=$member_id;
                        $upData['back']=2;
                        $upData['update_time']=time();
                        $upData['protection_time']=time();
                        $res=db($tabName)->where(['id'=>$cur['id']])->update($upData);
                        if(!$res){
                            $error[]=$cur['company_name'];
                        }
                        $com->companyLog($exhibition_id,'潜在展商-提取往届数据',$member_id,$cur['id']);
                    }
                }else{
                    $insData=db('company')->where(['id'=>$ids[$i]])->find();
                    if($insData){
                        unset($insData['id']);
                        $insData['member_id']=$member_id;
                        $insData['sale_id']=$member_id;
                        $insData['back']=2;
                        $insData['update_time']=time();
                        $insData['create_time']=time();
                        $insData['protection_time']=time();
                        $insData['company_id1']=$ids[$i];
                        $result=db($tabName)->insertGetId($insData);
                        if($result){
                            $com->companyLog($exhibition_id,'潜在展商-提取往届数据',$member_id,$result);
                        }else{
                            $error[]=$insData['company_name'];
                        }
                    }else{
                        $defect[]=$ids[$i];
                    }
                }
            }

            return json(['code' => 1, 'msg' => '操作成功','data'=>array('seize'=>$seize,'error'=>$error,'defect'=>$defect)]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function getCornerList()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            if(!$exhibition_id){
                return json(array('code' => '0', 'msg' => '展会错误'));
            }
            $res=db('exhibition_corner')->where(['exhibition_id'=>$exhibition_id,'is_delete'=>0])->select();
            return json(array('code' => '1', 'msg' => '成功','data'=>$res));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    // 成交展商excel导出  stj ce
    public function dealExport()
    {
        $exhibition_id = $this->request->param('exhibition_id');
        $exRes=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
        if(!$exRes){
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        $tabNames=$this->getTabName($exhibition_id);
        $param=" c.id_zs in (SELECT id FROM crm_".$tabNames." WHERE status>=5) AND c.is_delete=0 AND c.id_zhui=".$exhibition_id;
        $sql="SELECT c.id,c.id_zs,c.id_zwei,c.id_zhui,o.old_label,f.finance_total,f.finance_pay_time,a.realname,kp.billing_num,z.company_name,z.company_name_en,z.data_from,z.status as zh_status,z.company_id1,z.member_id,z.area_city,z.province FROM crm_contract AS c ";
        $sql.=" LEFT JOIN crm_".$tabNames." AS z ON z.id=c.id_zs ";
        $sql.=" LEFT JOIN crm_admin AS a ON a.id=z.member_id ";
        $sql.=" LEFT JOIN (SELECT MAX(id),label as old_label,company_id FROM crm_company_label WHERE label='老展商' AND exhibition_id=".$exhibition_id." GROUP BY company_id ) AS o ON o.company_id=z.company_id1";
        $sql.=" LEFT JOIN (SELECT COUNT(id) as billing_num,company_id FROM crm_billing WHERE is_delete=0 AND billing_status=2 AND exhibition_id=".$exhibition_id." GROUP BY company_id ) AS kp ON kp.company_id=z.id";
        $sql.=" LEFT JOIN (SELECT SUM(fee) as finance_total,contract_id, MAX(pay_time) as finance_pay_time FROM crm_finance WHERE is_delete=0 GROUP BY contract_id ) AS f ON f.contract_id=c.id";
        $sql.=" where 1=1 AND $param";
//        $sql.=" limit 1,2 ";
        $list=Db::query($sql);
        if(count($list) == 0 ){
            return json(['code'=>0,'msg'=>'暂无数据','data'=>'']);
        }
        $ids=[];
        foreach($list as &$val){
            if($val['id_zwei'])$ids[]=$val['id_zwei'];
        }
        $bSql="SELECT b.id,b.number,b.pavilion_id,b.area,p.title,pt.title as booth_price_type FROM crm_booth AS b ";
        $bSql.=" LEFT JOIN crm_hall as p ON p.id=b.hall_id ";
        $bSql.=" LEFT JOIN crm_booth_mold as pt ON pt.id=b.price_type ";
        $bSql.=" WHERE b.id IN (".implode(',', $ids).") ";
        $boothList=Db::query($bSql);
        foreach($list as &$v){
            $v['pavilion_num']='';
            $v['booth_price_type']='';
            $v['booth_area']='';
            $v['status_title']=$v['zh_status']==5?'部分付款':'全部付款';
            $v['finance_pay_time']=date("Y-m-d",$v['finance_pay_time']);
            if($v['id_zwei']){
                if(strpos($v['id_zwei'],",")){
                    $bids = explode(",", $v['id_zwei']);
                    $pNum='';
                    $price_type='';
                    $area='';
                    foreach($boothList as &$vv){
                        foreach($bids as &$vvv){
                            if($vvv == $vv['id']){
                                $pNum.=$vv['title'].'-'.$vv['number'].' ';
                                $price_type.=$vv['booth_price_type'].' ';
                                $area.=$vv['area'].' ';
                            }
                        }
                    }
                    $v['pavilion_num']=$pNum;
                    $v['booth_price_type']=$price_type;
                    $v['booth_area']=$area;
                }else{
                    foreach($boothList as &$vv){
                        if($v['id_zwei'] == $vv['id']){
                            $v['pavilion_num']=$vv['title'].'-'.$vv['number'];
                            $v['booth_price_type']=$vv['booth_price_type'];
                            $v['booth_area']=$vv['area'];
                        }
                    }
                }
            }

        }
        $title = "成交展商明细";
        $columns=$this->dealbaseExcel();
        $filename = $title . date('Y-m-d-H-i', time()) . ".xls";
        return json(['code'=>1,'msg'=>'操作成功','data'=>['columns'=>$columns,'filename'=>$filename,'list'=>$list]]);
    }


    //导出基础数据
    public function dealbaseExcel(){
        $columns = array(
            array('title' => 'ID', 'field' => 'id', 'width' => 12,'code'=>'A'),
            array('title' => '展商名称', 'field' => 'company_name', 'width' => 12,'code'=>'B'),
            array('title' => '展商英文名称', 'field' => 'company_name_en', 'width' => 12,'code'=>'C'),
            array('title' => '数据来源', 'field' => 'data_from', 'width' => 12),
            array('title' => '是否新老展商', 'field' => 'old_label', 'width' => 12),
            array('title' => '付款状态', 'field' => 'status_title', 'width' => 12),
            array('title' => '付款金额', 'field' => 'finance_total', 'width' => 12),
            array('title' => '付款时间', 'field' => 'finance_pay_time', 'width' => 12,'code'=>'D'),
            array('title' => '业务员', 'field' => 'realname', 'width' => 12,'code'=>'D'),
            array('title' => '展厅及展位号', 'field' => 'pavilion_num', 'width' => 12,'code'=>'E'),
            array('title' => '展位类别', 'field' => 'booth_price_type', 'width' => 12,'code'=>'F'),
            array('title' => '展位面积', 'field' => 'booth_area', 'width' => 12,'code'=>'F'),
            array('title' => '省份', 'field' => 'province', 'width' => 24,'code'=>'J'),
            array('title' => '城市', 'field' => 'area_city', 'width' => 24,'code'=>'J'),
            array('title' => '开票数量', 'field' => 'billing_num', 'width' => 24,'code'=>'J'),
        );

        return $columns;
    }


    public function changeBadgeNum(){
        $label_2 = $this->request->param('label_2');
        $exhibition_id = $this->request->param('exhibition_id');
        $exRes=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
        if(!$exRes){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        $id = $this->request->param('id');
        $tabNames=$this->getTabName($exhibition_id);
        $bsRes=db($tabNames)->where(['id'=>$id])->find();
        if(!$bsRes){
            return json(['code'=>0,'msg'=>'展商信息错误']);
        }
        $res=db($tabNames)->where(['id'=>$id])->update(['label_2'=>$label_2]);
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

}
